<?php

function query_from_memcache($query, $result = NULL) {
    $key = "q_" . md5($query);
    static $memcache = FALSE;
    if (!$memcache) {        
        global $GS_CONFIG;
        $host = $GS_CONFIG->memcache;
        $port = 11211;
        $memcache = new Memcache();
        $memcache->addServer($host, $port);
        $stats = @$memcache->getExtendedStats();
        $available = (bool) $stats["$host:$port"];
        if (!( $available && @$memcache->connect($host, $port))) {
            return $result;
        }
    }

    if (empty($result)) {
        $cached_result = $memcache->get($key);
//        echo "hit cache OK";
        return $cached_result;
    } else {
        $memcache->set($key, $result, false, 60);
//        echo "set cache OK";
        return $result;
    }
}

// SELECT QUERY WIth memcache enable = true
function safe_select_query2($query) {
    try {
        $result = query_from_memcache($query);
        if (empty($result)) {
            $result = get_data($query);
            return query_from_memcache($query, $result);
        }
        return $result;
    } catch (DatabaseException $de) {
        return null;
    }
}

// SELECT QUERY
function safe_select_query($query) {
    try {
        return get_data($query);
    } catch (DatabaseException $de) {
        return null;
    }
}

// INSERT QUERY
function safe_insert_query($query) {
    try {
        return insert_data($query);
    } catch (DatabaseException $de) {
        return null;
    }
}

// UPDATE QUERY
function safe_update_query($query) {
    try {
        return update_data($query);
    } catch (DatabaseException $de) {
        return null;
    }
}

// DELETE QUERY
function safe_delete_query($query) {
    try {
        return delete_data($query);
    } catch (DatabaseException $de) {
        return null;
    }
}

?>